package com.frinder.netty.discard;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by kiktech on 2017/8/3.
 */
public class DiscardServerHandler extends ChannelInboundHandlerAdapter {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 每当从客户端收到新的数据时，这个方法会在收到消息时被调用
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        logger.info("{} : {}", ctx, msg);
//        // 丢弃读到的消息
//        ((ByteBuf) msg).release();
        ByteBuf in = (ByteBuf) msg;
        System.out.print(in.toString(CharsetUtil.UTF_8));
//        ReferenceCountUtil.release(msg);
        in.release();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.info("{} : {}", ctx, cause);
        cause.printStackTrace();
        // 异常时关闭连接
        ctx.close();
    }
}
